package com.example.part.service.webscoket;


import com.alibaba.fastjson.JSON;
import com.example.part.bean.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


@ServerEndpoint(value = "/websocket/{senderId}")
@Component
@Slf4j
public class WebSocketServer {



	 //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    //线程安全的排序set
    public static Set<String> onlineUserSet = Collections.synchronizedSet(new LinkedHashSet<>());

    //发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                log.info("发送数据：" + message);
                session.getBasicRemote().sendText(message);
            }
        }
    }



    //给指定用户发送信息
    public void sendInfoToUser(String userName, String message){
        Session session = sessionPools.get(userName);
        try {
            sendMessage(session, message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }





    // 群发消息
    public void broadcast(String message){
    	for (Session session: sessionPools.values()) {
            try {
                sendMessage(session, message);
            } catch(Exception e){
                e.printStackTrace();
                continue;
            }
        }
    }




    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "senderId") String senderId){
        onlineUserSet.add(senderId);
        sessionPools.put(senderId, session);
        log.info(senderId + "加入webSocket！当前人数为" + onlineNum);

    }




    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "senderId") String userName){
        onlineUserSet.remove(userName);
        sessionPools.remove(userName);

        System.out.println(userName + "断开webSocket连接！当前人数为" + onlineUserSet.size());


    }

    //收到客户端信息后，根据接收人的username把消息推下去或者群发
    // to=-1群发消息
    @OnMessage
    public void onMessage(String message) throws IOException{

        System.out.println("server get--》" + message);
        Message msg=JSON.parseObject(message, Message.class);

        //对方挂断
        if ("hangup".equals(msg.contentType)) {
            msg.setContent("对方挂断！");
        }


        msg.setDate(new Date());
        if(onlineUserSet.contains(msg.getTo())){
            sendInfoToUser(msg.getTo(), JSON.toJSONString(msg,true));
        }else{
            System.out.println("对方不在线");

        }


    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
        log.error("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }

    public static AtomicInteger getOnlineNumber() {
        return onlineNum;
    }

    public static ConcurrentHashMap<String, Session> getSessionPools() {
        return sessionPools;
    }

    private static Set<String> getOnlineUserSetExclude(String userName){
        Set<String> onlineUsers = sessionPools.keySet();
        onlineUsers = new HashSet<>(onlineUsers);
        onlineUsers.remove(userName);
        return onlineUsers;
    }
}
